//redux 是解耦的, 你也可以不使用
import {createStore, Action, Reducer, Store, AnyAction, Dispatch} from 'redux';

const counterValue: HTMLElement | null = document.getElementById('conter-value') as HTMLParagraphElement;
const incrementBtn: HTMLElement | null = document.getElementById('increment') as HTMLButtonElement;
const decrementBtn: HTMLElement | null = document.getElementById('decrement') as HTMLButtonElement;

const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

interface State { //仓库的状态类型
    number: number;
}

const initialState: State = {number: 0};

// type CounterAction = AnyAction;

type CounterAction = Action<string> & {
    amount: number;
};

const reducer: Reducer<State, CounterAction> = (state: State = initialState, action: CounterAction) => {
  switch (action.type) {
  case INCREMENT:
    return {number: state.number + action.amount};
  case DECREMENT:
    return {number: state.number - action.amount};
  default:
    return state;
  }
};

const store: Store<State, CounterAction> = createStore<State, CounterAction, {}, {}>(reducer);
function render(){
    counterValue!.innerHTML = store.getState().number + '';
}

render();
store.subscribe(render);

const dispatch: Dispatch<CounterAction> = store.dispatch;
incrementBtn.addEventListener('click', (event: MouseEvent) => {
  dispatch({type: INCREMENT, amount: 2});
});

decrementBtn.addEventListener('click', (event: MouseEvent) => {
  dispatch({type: DECREMENT, amount:1});
});
